﻿using mozhi.smarterp.Finance.Accounts.Repository;
using mozhi.smarterp.Finance.Basedatas;
using mozhi.smarterp.Finance.Basedatas.ThirdParties;
using mozhi.smarterp.Finance.Enums;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using Volo.Abp;

namespace mozhi.smarterp.Finance.Ieps.Import
{
    public class ThirdPartyImportHandler : ImportHandlerBase<ThirdPartyDto>
    {
        private IAccountRepository _accountRepository;

        private IThirdPartyAppService _thirdPartyAppService;

        public ThirdPartyImportHandler(IServiceProvider serviceProvider) : base(serviceProvider)
        {
            _accountRepository = serviceProvider.GetService(typeof(IAccountRepository)) as IAccountRepository;
            _thirdPartyAppService = serviceProvider.GetService(typeof(IThirdPartyAppService)) as IThirdPartyAppService;
        }

        public override async Task<ImportResultDto> HandleImportData(Guid fileId)
        {
            var thirdParties = (await GetImportData(ModuleCodeType.Thirdparty, fileId)) as List<ThirdPartyDto>;

            await LoadAccountsAsync(thirdParties);

            var result = new ImportResultDto();

            result.Total = thirdParties.Count;

            result.Errors = new List<string>();

            //开始上传供应商
            for (int i = 0; i < thirdParties.Count; i++)
            {
                var thirdParty = thirdParties[i];

                var createDto = new ThirdPartyCreateDto();
                createDto.Name = thirdParty.Name;
                createDto.Code = thirdParty.Code;
                createDto.CurrentAccountId = thirdParty.CurrentAccountId;
                createDto.Activated = true;

                try
                {
                    await _thirdPartyAppService.CreateAsync(createDto);
                    result.SuccessfulCount += 1;
                }
                catch (UserFriendlyException ex)
                {
                    result.FailureCount += 1;
                    result.Errors.Add($"第{i + 1}行有错误：{ex.Message}");
                }
            }

            return result;
        }


        protected override List<ThirdPartyDto> ConvertToData(DataSet ds)
        {
            var result = new List<ThirdPartyDto>();

            var dt = ds.Tables[0];

            if (dt.Rows.Count == 0)
                return result;

            foreach (DataRow row in dt.Rows)
            {
                var thirdParty = new ThirdPartyDto();
                thirdParty.Code = row["Code"].ToString();
                thirdParty.Name = row["Name"].ToString();
                thirdParty.CurrentAccountName = row["CurrentAccountName"].ToString();

                result.Add(thirdParty);
            }

            return result;
        }

        #region
        private async Task LoadAccountsAsync(List<ThirdPartyDto> customers)
        {
            var accountNames = customers.Where(x => x.CurrentAccountName != null).Select(x => x.CurrentAccountName).Distinct().ToList();

            var accountCodes = new List<string>();

            foreach (var accountName in accountNames)
            {
                var splits = accountName.Split(' ');

                accountCodes.Add(splits[0]);
            }

            var accounts = await _accountRepository.FindAsync(new Querys.AccountQuery() { Codes = accountCodes });

            if (accounts.Count == 0)
                return;

            foreach (var customer in customers)
            {
                if (!customer.CurrentAccountName.IsNullOrEmpty())
                {
                    var splits = customer.CurrentAccountName.Split(' ');

                    var matchAccount = accounts.FirstOrDefault(x => x.Code == splits[0] || x.Name == splits[0]);

                    customer.CurrentAccountId = matchAccount == null ? default : matchAccount.Id;
                }
            }
        }
        #endregion
    }
}
